#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
# @FileName  :main.py
# @Time      :2022/8/19 13:31
# @Author    :Toliong toliong@foxmail.com
"""
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

from . import curd, schemas, models
from .database import SessionLocal, engine
import uvicorn


# 创建表
models.Base.metadata.create_all(bind=engine)

# 实例化应用
app = FastAPI()


# 创建数据库依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 创建用户
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = curd.get_user_by_email(db, email=user.email)
    print(type(user), user)
    if db_user:
        raise HTTPException(status_code=400, detail="Email already registered")
    return curd.create_user(db=db, user=user)


# 查询所有用户
@app.get("/users/", response_model=list[schemas.User])
def get_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = curd.get_users(db, skip, limit)
    return users


# 通过id查询用户
@app.get("/users/{user_id}", response_model=schemas.User)
def get_user(user_id: int, db: Session = Depends(get_db)):
    user = curd.get_user(db, user_id)
    if user is None:
        raise HTTPException(status_code=404, detail="user not found. ")
    return user


# 创建item
@app.post("/user/{user_id}/item", response_model=schemas.Item)
def create_user_item(user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db) ):
    db_item = curd.create_user_item(db,item, user_id)
    return db_item


# 查询所有item
@app.get("/item", response_model=list[schemas.Item])
def get_items(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    items = curd.get_items(db, skip, limit)
    return items
